<template>
  <el-dialog :title="showTitle" :visible="showDialog" @close="close">
    <!--表单内容-->
    <el-form :model="formData" :rules="formRules" ref="addDept" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" placeholder="2-10个字符" style="width: 80%;" size="mini"></el-input>
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" placeholder="2-10个字符" style="width: 80%;" size="mini"></el-input>
      </el-form-item>
      <el-form-item label="部门负责人" prop="managerId">
        <el-select v-model="formData.managerId" placeholder="请选择负责人" style="width: 80%;" size="mini">
          <el-option
            v-for="item in managerList"
            :key="item.id"
            :label="item.username"
            :value="item.id">
          </el-option>
        </el-select>

      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="formData.introduce" placeholder="1-100个字符" type="textarea" style="width: 80%;" size="mini"
                  :rows="4"></el-input>
      </el-form-item>
      <el-form-item>
        <el-row type="flex" justify="center">
          <el-col :span="12">
            <el-button type="primary" size="mini" @click="onSubmit">确认</el-button>
            <el-button size="mini" @click="close">取消</el-button>
          </el-col>
        </el-row>


      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
import {addDepartment, getDepartmentDetail, getmanagerList, updateDepartment} from "@/api/department";


export default {
  name: "AddDept",
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    depts: {
      type: Array,
      default: []
    },
    currentNodeId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      managerList: [],// 部门负责人列表
      // 表单数据
      formData: {
        code: "",// 部门编码
        introduce: "",// 部门介绍
        managerId: '',// 部门负责人
        name: "",// 部门名称
        pid: ""// 父级部门id

      },
      formRules: {
        name: [{required: true, message: '部门名称不能为空', trigger: 'blur'},
          {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'},
          // 自定义校验
          {
            validator: (rule, value, callback) => {
              //编辑场景下排除自身(如果id存在，则表示编辑状态)
              let result = this.depts
              if (this.formData.id) {
                // 编辑场景下排除滋生
                result = result.filter(item => item.id !== this.formData.id)
              }
              if (result.some(item => item.name === value)) {
                callback(new Error('部门名称已存在'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
    }
  ],
    code: [{required: true, message: '部门编号不能为空', trigger: 'blur'},
      {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'},
      // 自定义校验
      {
        validator: (rule, value, callback) => {
          let result = this.depts
          if (this.formData.id) {
            // 编辑场景下排除滋生
            result = result.filter(item => item.id !== this.formData.id)
          }
          if (result.some(item => item.code === value)) {
            callback(new Error('部门编号已存在'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }],
      managerId
  :
    [{required: true, message: '部门负责人不能为空', trigger: 'blur'}],
      introduce
  :
    [{required: true, message: '部门介绍不能为空', trigger: 'blur'},
      {min: 1, max: 100, message: '长度在 1 到 100个字符', trigger: 'blur'}]
  }
}
},
created()
{
  this.getmanagerList()
}
,
methods: {
  close()
  {
    // resetFields 只能重置在模板中绑定的数据
    this.formData = {
      code: '', // 部门编码
      introduce: '', // 部门介绍
      managerId: '', // 部门负责人id
      name: '', // 部门名称
      pid: '' // 父级部门的id
    }
    this.$refs.addDept.resetFields() // 重置表单
    this.$emit('update:showDialog', false)
    // 修改父组件中的数据，子传父
    this.$emit('update:showDialog', false)
  },
  async getmanagerList()
  {
    this.managerList = await getmanagerList()
  }
,
  // 确认
  onSubmit()
  {
    this.$refs.addDept.validate(async (vaild) => {
      if (vaild) {
        let msg="新增"
        // 区分场景
        if(this.formData.id){
          await updateDepartment(this.formData)
          msg="更新"
        }else{
          await addDepartment({...this.formData, pid: this.currentNodeId})
        }

        // 通知父组件更新，重新获取组织数据
        this.$emit('updateDepartment')
        // 提示消息
        this.$message.success(`${msg}部门成功`)
        // 关闭弹窗
        this.close()
      }
    })
  }
,
  // 获取部门详情
  async getDepartmentDetail(id)
  {
    this.formData = await getDepartmentDetail(id)
  }

}
,
computed:{
  showTitle()
  {
    return this.formData.id ? '编辑部门':'新增部门'
  }
}
}
</script>
<style scoped></style>
